package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.NcGoods;
import com.ruoyi.system.domain.NcGoodsLog;
import com.ruoyi.system.domain.NcMeterial;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.INcGoodsLogService;
import com.ruoyi.system.service.INcGoodsService;
import com.ruoyi.system.service.INcMeterialService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.util.ExcelUtil2;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 物资仓储存 信息操作处理
 *
 * @author ruoyi
 * @date 2019-08-05
 */
@Controller
@RequestMapping("/system/ncGoods")
public class NcGoodsController extends BaseController
{
    private String prefix = "system/ncGoods";

    private String frontPrefix = "system/ncGoods/front";

	@Autowired
	private INcGoodsService ncGoodsService;

	@Autowired
	private INcGoodsLogService ncGoodsLogService;

	@Autowired
	private INcMeterialService ncMeterialService;

	@Autowired
	private ISysUserService iSysUserService;

	@RequiresPermissions("system:ncGoods:view")
	@GetMapping()
	public String ncGoods()
	{
	    return prefix + "/ncGoods";
	}

	@GetMapping("/front")
	public String frontNcGoods(){
		return frontPrefix + "/ncGoods";
	}

	@GetMapping("/merial")
	public String frontNcGoodsMerial(NcGoods ncGoods,@RequestParam(value = "beginTime",required = false)String beginTime
			, @RequestParam(value = "endTime",required = false)String endTime,ModelMap mmap){
		if (StringUtils.isNotEmpty(beginTime)) {
			ncGoods.getParams().put("beginTime", beginTime);
		}
		if (StringUtils.isNotEmpty(endTime)) {
			ncGoods.getParams().put("endTime", endTime);
		}
		mmap.put("beginTime", beginTime);
		mmap.put("endTime", endTime);
		ncMeterialService.SelectNcGoodsMeter(mmap,ncGoods);
		return frontPrefix + "/ncGoodsMerial";
	}
	/**
	 *
	 * @param dataSpan   时间跨度 1:年 2：月 3：日
	 * @return
	 */
	@PostMapping("/goodsQuery")
	@ResponseBody
	public TableDataInfo chickenQuery(Integer dataSpan,String  beginTime, String endTime,String metialType){
		List<Map> list = ncGoodsService.selectCountByTime(dataSpan,beginTime,endTime,metialType);
		return getDataTable(list);
	}

	@GetMapping("/frontGoodsSortMeterial")
	public String frontGoodsSortMeterial(String type,String beginTime,String endTime,ModelMap mmap){
		List<NcMeterial> list = ncMeterialService.selectMeterialFirstSort(0);
		String val = "";
		for(NcMeterial nmt : list){
			if(Long.parseLong(type) == nmt.getMeterialId()){
				val = nmt.getMeterialName();
			}
		}
		mmap.put("type",type);
		mmap.put("beginTime",beginTime);
		mmap.put("endTime",endTime);
		mmap.put("meterList",list);
		mmap.put("val",val);
		return frontPrefix + "/ncGoodsSortMeter";
	}

	/**
	 * 前端的分类列表物资
	 */
	@PostMapping("/frontGoodsSortList")
	@ResponseBody
	public TableDataInfo frontGoodsSortList(String type,String beginTime,String endTime)
	{
		startPage();
		List<NcGoods> list = ncGoodsService.selectNcGoodsByMeterialId(type,beginTime,endTime);
		return getDataTable(list);
	}



	/**
	 * 查询物资仓储存列表
	 */
	@RequiresPermissions("system:ncGoods:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(NcGoods ncGoods)
	{
		startPage();
        List<NcGoods> list = ncGoodsService.selectNcGoodsList(ncGoods);
		return getDataTable(list);
	}


	/**
	 * 导出物资仓储存列表
	 */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcGoods ncGoods)
    {
    	List<NcGoods> list = ncGoodsService.selectNcGoodsList(ncGoods);
//        ExcelUtil<NcGoods> util = new ExcelUtil<NcGoods>(NcGoods.class);
		ExcelUtil2<NcGoods> util = new ExcelUtil2<>(NcGoods.class);
		return util.exportExcel(list, "物资管理单");
    }

	/**
	 * 新增物资仓储存
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap)
	{
		mmap.put("users",iSysUserService.selectUserList(new SysUser()));
	    return prefix + "/add";
	}

	/**
	 * 出入库记录
	 */
	@RequiresPermissions("system:ncGoods:depot")
	@Log(title = "出库", businessType = BusinessType.INSERT)
	@GetMapping("/depot/{goodsId}")
	public String depot(@PathVariable("goodsId")Long goodsId , ModelMap mmap){
		mmap.put("depot",ncGoodsService.selectNcGoodsById(goodsId));
		mmap.put("users",iSysUserService.selectUserList(new SysUser()));


		return prefix + "/depot";
	}

	/**
	 * 出入库记录保存
	 */
	@RequiresPermissions("system:ncGoods:depot")
	@Log(title = "物资管理", businessType = BusinessType.INSERT)
	@PostMapping("/depot")
	@ResponseBody
	public AjaxResult addSave(NcGoodsLog ncGoodsLog)
	{
		SysUser sysUser = ShiroUtils.getSysUser();
		ncGoodsLog.setCreateBy(sysUser.getLoginName());
		ncGoodsLog.setCreateTime(new Date());

		//库存不够出库量 提示库存不足
//		List<NcGoodsLog> ncGoodsLogs = ncGoodsLogService.selectNcGoodsLogByGId(ncGoodsLog.getGoodsId());
		NcGoods ncGoodsLogs = ncGoodsService.selectNcGoodsById(ncGoodsLog.getGoodsId());
		if (ncGoodsLogs.getStockAmout() !=null) {

			if((ncGoodsLogs.getStockAmout())>=ncGoodsLog.getOutputAmount()){
				NcGoods ncGoods = new NcGoods();
				ncGoods.setStockAmout(ncGoodsLogs.getStockAmout()-ncGoodsLog.getOutputAmount());
				ncGoods.setGoodsId(ncGoodsLog.getGoodsId());
				ncGoodsService.updateNcGoods(ncGoods);//更新出库后的库存
				ncGoodsLog.setStockAmout(ncGoodsLogs.getStockAmout()-ncGoodsLog.getOutputAmount());
				return toAjax(ncGoodsLogService.insertNcGoodsLog(ncGoodsLog));

			}
		return AjaxResult.error("库存不足");
		}
		return AjaxResult.error("库存为空");

	}


	/**
	 * 新增保存物资仓储存
	 */
	@RequiresPermissions("system:ncGoods:add")
	@Log(title = "物资仓储存", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(NcGoods ncGoods)
	{
		/*SysUser sysUser = ShiroUtils.getSysUser();
		ncGoods.setCreateBy(sysUser.getLoginName()); //拿到登录的用户名*/

		//设置物资批次
		ncGoods.setGoodsCode(NcUtils.getmeterialCode());

		try {

			if (ncGoods.getInputAmount() !=0 && !("").equals(ncGoods.getInputAmount())) {

				if (ncGoods.getInputAmount() >=0) {
					ncGoods.setStockAmout(ncGoods.getInputAmount());
					return toAjax(ncGoodsService.insertNcGoods(ncGoods));
				}else {
					return AjaxResult.error("不能为负数");
				}
			} else {
				return AjaxResult.error("数量为空");
			}
		}catch (Exception e){
			return AjaxResult.error("不能为小数");
		}



	}

	/**
	 * 修改物资仓储存
	 */
	@GetMapping("/edit/{goodsId}")
	public String edit(@PathVariable("goodsId") Long goodsId, ModelMap mmap)
	{
		NcGoods ncGoods = ncGoodsService.selectNcGoodsById(goodsId);
		mmap.put("ncGoods", ncGoods);

		List<SysUser> sysUsers = iSysUserService.selectUserList(new SysUser());
		if(ncGoods!=null && StringUtils.isNotNull(ncGoods.getPurchaser())){
			for (SysUser sysUser : sysUsers) {
				if((""+sysUser.getUserId()) .equals(ncGoods.getPurchaser())){
					sysUser.setFlag(true);
					break;
				}
			}

		}
		mmap.put("purchaser",sysUsers);

		List<SysUser> sysUseres = iSysUserService.selectUserList(new SysUser());
		if(ncGoods!=null && StringUtils.isNotNull(ncGoods.getCreateBy())){
			for (SysUser sysUsere : sysUseres) {
				if((""+sysUsere.getUserId()) .equals(ncGoods.getCreateBy())){
					sysUsere.setFlag(true);
					break;
				}
			}
		}
		mmap.put("createBy",sysUseres);
		System.out.println(ncGoods.getUnit());

		return prefix + "/edit";
	}

	/**
	 * 修改保存物资仓储存
	 */
	@RequiresPermissions("system:ncGoods:edit")
	@Log(title = "物资仓储存", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(NcGoods ncGoods)
	{
		List<NcMeterial> ncMeterials = ncMeterialService.selectMeterialIdByName(ncGoods.getMeterialName());
		for (NcMeterial ncMeterial : ncMeterials) {
			ncGoods.setMeterialId(ncMeterial.getMeterialId());
		}

		return toAjax(ncGoodsService.updateNcGoods(ncGoods));

	}

	/**
	 * 删除物资仓储存
	 */
	@RequiresPermissions("system:ncGoods:remove")
	@Log(title = "物资仓储存", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		return toAjax(ncGoodsService.deleteNcGoodsByIds(ids));
	}

}
